﻿<%@ WebHandler Language="C#" Class="imageHandler" %>

using System;
using System.Web;
using System.IO;
using Business;

public class imageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";

        HttpPostedFile file = context.Request.Files["Filedata"];
        //string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";


        string email = context.Request.Params["email"].Trim().ToString();
        //email = email.Trim().ToString();
        string fileidname = context.Request.Params["fileidname"].Trim().ToString();


        string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\" + email + "\\userinfo\\";
        
            
        if (file != null)
        {
            //if (File.Exists(uploadPath + file.FileName))
            //{
            //    context.Response.Write("3");            //文件已经存在
            //    return;
            //}

            string[] fn = file.FileName.Split('.');
          
            //存在删除
            string[] filetype = new string[4];
            filetype[0] = email + ".png";
            filetype[1] = email + ".jpg";
            filetype[2] = email + ".gif";
            filetype[3] = email + ".jpeg";
            for (int i = 0; i < filetype.Length;i++ )
            {
                if (File.Exists(uploadPath + filetype[i]))
                {
                    File.Delete(uploadPath + filetype[i]);
                } 
            }

            //存储
            string ext = fn[fn.Length - 1];   //后缀
            //string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + "." + ext;
            string filename = fileidname + "." + ext;
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }

            string dbsavefilename = "../../Content/UserImageDB/" + email + "/userinfo/" + filename;
            if (Business.ImageManage.Userinfo(email,dbsavefilename))
            {
                file.SaveAs(uploadPath + filename);
            }
            //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
           // context.Session[context.Session["userName"].ToString()] = filename;       //这里书写有点不规范

            context.Response.Write(filename);
        }
        else
        {
            context.Response.Write("0");
        }  
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}